package dao.serialization;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Collection;

import model.ModelBase;
import dao.DAO;

public class AbstractSerializationDAO<T> implements DAO<T>
{

  @SuppressWarnings("unchecked")
  public T read(InputStream in) throws IOException 
  {
    if (in == null) 
    { 
    	throw new IllegalArgumentException("input must not be null!"); 
    }
    try 
    {
      ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(in));
      return (T) ois.readObject();
    }
    catch (ClassNotFoundException e) 
    {
      throw new IOException("cannot find necessary class!", e);
    }
  }

  @SuppressWarnings("unchecked")
  public Collection<T> readMultiple(InputStream in) throws IOException 
  {
    if (in == null) 
    { 
    	throw new IllegalArgumentException("input must not be null!"); 
    }
    try 
    {
      ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(in));
      return (Collection<T>) ois.readObject();
    }
    catch (ClassNotFoundException e) 
    {
      throw new IOException("cannot find necessary class!", e);
    }
  }

  public void write(OutputStream out, T data) throws IOException 
  {
    if (out == null) 
    { 
    	throw new IllegalArgumentException("output must not be null!"); 
    }
    if (data == null) 
    { 
    	throw new IllegalArgumentException("data must not be null!"); 
    }
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(out));
    oos.writeObject(data);
    oos.flush();
  }

  public void writeMultiple(OutputStream out, Collection<T> data) throws IOException 
  {
    if (out == null) 
    { 
    	throw new IllegalArgumentException("output must not be null!"); 
    }
    if (data == null) 
    { 
    	throw new IllegalArgumentException("data must not be null!"); 
    }
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(out));
    oos.writeObject(data);
    oos.flush();
  }
	@Override
	public int delete(Connection connection, ModelBase data) 
	{
		return 0;
	}
	
	@Override
	public int save(Connection connection, ModelBase data) 
	{
		return 0;
	}
}
